<script setup lang="ts">
	import { ref, onMounted, onUnmounted, watch, reactive } from 'vue'
	import { getHomeBanner, getHomeCategory, getHome, getUserDeviceData,getDoctorData } from '@/services/home';
	import { getScanAPI, getUserAPI } from '@/services/hot';
	import { useMemberStore } from '@/stores'
	import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
	// import { onLoad } from '@dcloudio/uni-app';
	// import CustomNavbar from './components/CustomNavbar.vue'
	// import CategoryPanel from './components/CategoryPanel.vue'
	// import HomePanel from './components/HomePanel.vue';
	import { onShow } from '@dcloudio/uni-app'
	// import { useGuessList } from '@/composables';
	const bannerList = [
		{ id: 1, imgUrl: 'https://img.51miz.com/preview/element/00/01/13/60/E-1136003-EC3A96C1.jpg' },
		{ id: 2, imgUrl: 'https://ts1.cn.mm.bing.net/th/id/R-C.3ee3bd7e2c4a4be72df4aec4cdf707a4?rik=HdqXMqHXyS6imA&riu=http%3a%2f%2fpic.ntimg.cn%2ffile%2f20190423%2f19603530_170014837488_2.jpg&ehk=vt2AnhWaviLj9pkeS9%2fsf64wjIkQ%2bWa2ZYjgLGb74OY%3d&risl=&pid=ImgRaw&r=0' }
	]
	const backendResponse = ref([]); // 保存后端返回的信息
	const memberStore = useMemberStore()
	const scannedDeviceId = ref('');
	const showForm = ref<boolean>(false);
	let userId = null;
  const selectedRecordOriginalId = ref(null);
	/**
	 * 生命周期
	 */
	onMounted(() => {
		console.log('生命周期被执行啦')
	})
	onShow(() => {
		if (memberStore.profile) {
			userId = memberStore.profile.userId
		}
		console.log(userId, '备注', memberStore.profile?.userId)
	})
	/**
	 * 变量
	 */
  // 医生建议信息
const doctorAdvice = ref('');
	//当前的信息
	let record = ref({})
	// 设备列表
	const deviceShow = ref(false);
	// 设备使用者
	const userDeviceShow = ref(false);
	//用户信息时间
	const userTimeShow = ref(false)
	const deviceData = ref([])
	//用户信息
	const userColumns = ref([]);
	// 用户实际
	const timeColumns = ref([
	])
	const selectClose = () => {
		deviceShow.value = false
	}
	const userSelectClose = () => {
		userDeviceShow.value = false
	}
	const timeSelectClose = () => {
		userTimeShow.value = false
	}
	//点击确认事件
	const deviceBtn = (e) => {
		// 关闭弹框
		selectClose()
	}
	//用户选择了那个用户信息
	const userSelctBtn = (e) => {
		console.log(e, '用户')
		handleDetailed(e.value[0].userId)
    // doctorData(e.value[0].recordOriginalId)
		//关闭弹框
		userSelectClose()
	}
	// 时间的选择
	const timeSelctBtn = (e) => {
		console.log(e, '时间')
		record.value = e.value[0]
     selectedRecordOriginalId.value = record.value.recordOriginalId;
    fetchDoctorData(record.value.recordOriginalId)
		// 时间弹框关闭
		timeSelectClose()
	}
   const isDeviceBound = ref(false);
watch(() => memberStore.profile, (newValue, oldValue) => {
  if (!newValue && oldValue) {
    // 用户退出登录
    // 清除用户信息
    clearUserInfo();
    // 展示扫码查询页面
    // showScanQueryPage();
  }
});

// 清除用户信息
const clearUserInfo = () => {
  // 清空相关数据或重置为初始状态
  record.value = {};
  scannedDeviceId.value = '';
  showForm.value = false;
   isDeviceBound.value = false; // 清除设备信息时重置标志
};
	// 用户列表弹框状态值
	const userShow = ref(false)
	//用户列表
	const userList = ref([])

	const navigateToAIPage = (recordOriginalId) => {
		uni.navigateTo({
			url: '/pageMember/AI/AI?recordId=' + recordOriginalId
		});
	};
	// 调用相机的扫一扫
	const startScan = async () => {
		try {
			if (!memberStore.profile) {
				uni.showModal({
					content: '请先登录',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						}
					}
				});
				return;
			}
			// 检查设备是否已绑定
			if (scannedDeviceId.value) {
				// 设备已绑定
				uni.showModal({
					content: '用户已绑定设备',
					showCancel: false
				});
			} else {
				// 设备未绑定，继续扫描流程
				const res = await wx.scanCode();
				scannedDeviceId.value = res.result;
				uni.setStorageSync('scannedDeviceId', scannedDeviceId.value);
				showForm.value = true; // 扫描后显示表单
			}
		} catch (error) {
			console.error("扫描失败：", error);
		}
	};
  // 绑定设备
	const bindDevice = async () => {
		try {
			const response = await getScanAPI({ deviceCode: scannedDeviceId.value, userId: userId });
			showForm.value = false;
       isDeviceBound.value = true;
			// 更新后端响应
			uni.showModal({
				content: response.code === 20000 ? '绑定设备成功，请查询用户信息' : '设备已绑定，请查询用户信息',
				success: async (res) => {
					if (res.confirm) {
						const useRes = await getUserAPI(scannedDeviceId.value);
						if (useRes.code === 20000) {
							console.log(useRes);
							if (useRes.data.userDeviceVOList.length > 0) {
								userList.value = useRes.data.userDeviceVOList;
								userShow.value = true;
							} else {
								userShow.value = false;
								uni.showModal({
									content: '暂无用户信息，请重新扫码查询',
									showCancel: false
								});
							}
						} else {
							console.log('数据', useRes);
						}
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		} catch (error) {
			console.error("设备绑定失败：", error);
		}
	};
	// onShow(async () => {
	// 	const res = await getHome(6)
	// 	console.log(res)
	// 	if (res.data) {
	// 		backendResponse.value = res.data.recordInfoVOList;
	// 	}
	// })
	const recordOriginal = ref([])
	// 是否加载标记
	let userInfoId = ref();
	const isRefreshing = ref(false);
	const scrollViewHeight = ref('400px');
	// 刷新数据的方法
	const refreshData = () => {
    if (!isDeviceBound.value) {
                console.log("设备未绑定。无法刷新数据。");
                return; // 如果设备未绑定，提前退出
            }
		console.log(111111111111111111)
		isRefreshing.value = true;
		handleDetailed(userInfoId.value)
     fetchDoctorData(selectedRecordOriginalId.value);
		setTimeout(() => {
			isRefreshing.value = false;
		}, 2000)
	};
	let throttleTimer = ref()
	// 下拉事件被复位
	const onRestore = (e) => {
		isRefreshing.value = false;
		console.log("onRestore", e);
	}
	const onPulling = (e : any) => {
		if (!throttleTimer.value) {
			// 如果节流定时器不存在，则执行点击逻辑，并设置定时器
			console.log('Button clicked');
			throttleTimer.value = setTimeout(() => {
				// 1秒后清除定时器，允许下一次点击
				throttleTimer.value = null;
				// refreshData()
			}, 1000); // 设置节流时间间隔为1秒
		} else {
			// 如果节流定时器存在，则表示函数已经在节流中，不执行点击逻辑
			console.log('Function is throttled');
		}
		console.log("onpulling", e);
	}
	// 定义一个 ref 来表示刷新状态
	// 设备信息弹框关闭事件
	const infoClose = () => {
		showForm.value = false
	}
	// 用户的详情数据  传递用户id
	const handleDetailed = async (userId) => {
	    // 重置设备信息和用户列表
       // doctorAdvice.value = '';
	    deviceData.value = [];
	    userColumns.value = [];
	    // 查询用户绑定设备信息
	    await getUserDeviceInfo(userId);
	    // 获取用户列表信息
	    await getUserInfoList(scannedDeviceId.value);
	    userInfoId.value = userId;
	    // 先清空时间列
	    timeColumns.value = [];
	    const codeRes = await getHome(userId);
	    if (codeRes.code === 20000) {
	        if (codeRes.data.recordInfoVOList.length === 0) {
	            uni.showModal({
	                content: '暂无用户信息，请重新扫码查询'
	            });
	        }
	        // 将用户信息时间添加到时间列中
	        timeColumns.value.push(codeRes.data.recordInfoVOList);
	        // 选择最新的记录
	        record.value = codeRes.data.recordInfoVOList[codeRes.data.recordInfoVOList.length - 1];
	        // 排序数据
	        codeRes.data.recordInfoVOList.sort((a, b) => b.recordOriginalId - a.recordOriginalId);
	        backendResponse.value = codeRes.data.recordInfoVOList;
	        // 获取最新记录的 recordOriginalId
            const latestRecordOriginalId = codeRes.data.recordInfoVOList[0].recordOriginalId;
                            // 获取医生建议数据并更新
                            if (!selectedRecordOriginalId.value) {
                                           // 如果没有选择时间，则默认展示最新记录的医生建议
                                           await fetchDoctorData(latestRecordOriginalId);
                                       }
	        // const latestRecordOriginalId = codeRes.data.recordInfoVOList[0].recordOriginalId;
	        // // 获取医生建议数据并更新
	        // await fetchDoctorData(latestRecordOriginalId);
	        // 关闭用户列表
	        userShow.value = false;
	    }
	};

  // 获取医生建议数据
  const fetchDoctorData = async (recordOriginalId) => {
      try {
           const response = await getDoctorData(recordOriginalId);
                  doctorAdvice.value = response.data.doctorAdvice || '暂无';
      } catch (error) {
          console.error("获取医生建议数据时出错：", error);
          // 如有需要，处理错误
      }
  };

	//获取用户绑定的设备信息
	const getUserDeviceInfo = async (userId) => {
		//先清空数据
		deviceData.value = []
		const res = await getUserDeviceData(userId)
		if (res.code == 20000) {
			deviceData.value.push(res.data.userDeviceBindVOList)
			console.log(deviceData.value, 7777777777777777)
		} else {
			uni.showModal({
				content: '查询用户绑定的设备失败'
			})
		}
	}
	// 获取的当前的用户列表信息
	const getUserInfoList = async (scannedDeviceId) => {
		//先清空数据
		userColumns.value = []
		const res = await getUserAPI(scannedDeviceId)
		if (res.code == 20000) {
			userColumns.value.push(res.data.userDeviceVOList)
		} else {
			uni.showModal({
				content: '查询用户信息列表失败'
			})
		}
		console.log(res, '设备的用户')
	}
</script>
<template>
	<!-- 头部搜索区域 -->
	<view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
		<view class="logo"></view>
		<!-- 搜索条 -->
		<view class="search">
			<text class="icon-scan" @tap="startScan"></text>
			<!-- <text class="icon-search">搜索</text> -->
		</view>
	</view>
	<!-- <view class="scroll-view"> -->
	<!-- 设备信息弹框 -->
	<!-- showForm -->
	<view class="scroll-view" @pulling="onPulling" @restore="onRestore">
		<u-popup closeable="true" mode="bottom" :show="showForm" :round="6" closeOnClickOverlay="true"
			@close="infoClose">
			<view class="device-info">
				<view class="form-row">
					<text class="label">设备唯一编码：</text>
					<text class="value">{{ scannedDeviceId }}</text>
				</view>
				<view class="form-buttons">
					<button @click="bindDevice">绑定设备</button>
					<!-- <button @click="queryUserInfo">查询用户信息</button> -->
				</view>
			</view>
		</u-popup>
		<!-- 设备绑定的用户列表 -->
		<!-- userName -->
		<u-popup :show="userShow" mode="top">
			<view style="text-align: center;">用户信息列表</view>
			<u-list :height="300">
				<u-list-item v-for="(item, index) in userList" :key="index">
					<u-cell :title="item.userName" @click="handleDetailed(item.userId)">
					</u-cell>
				</u-list-item>
			</u-list>
		</u-popup>
	</view>
	<yooSwiper :list="bannerList"></yooSwiper>
	<!-- :style="{ height: scrollViewHeight }" -->
   <scroll-view :refresher-threshold="100" refresher-background="#F0F0F4" :refresher-enabled="isDeviceBound" style="height:800px"
		@refresherpulling="onPulling" @refresherrefresh="refreshData()" @refresherrestore="onRestore"
		:refresher-triggered="isRefreshing"  class="scroll-view" scroll-y >
	<view class="select-list" v-if="record.createTime" ref="scrollView" @pulling="onPulling" @restore="onRestore">
		<view class="select-item" @click="deviceShow=true">
			设备列表
			<up-icon name="arrow-right" size="10px"></up-icon>
		</view>
		<view class="select-item" @click="userDeviceShow = true">
			更改用户
			<up-icon name="arrow-right" size="10px"></up-icon>
		</view>
		<view class="select-item" @click="userTimeShow = true">
			选择查询时间
			<up-icon name="arrow-right" size="10px"></up-icon>
		</view>
	</view>
	<view class="scroll-view">
		<view class="login-blank" v-if="!record.createTime">
			<!-- <view class="card" @click="startScan">
				<text>扫码查询</text>
			</view> -->
      <button class="button" @click="startScan">扫码查询</button>
		</view>
  <!--  <view class="login-blank" v-else>
      <text class="text">登录后可查看留言信息</text>
      <navigator url="/pages/login/login" hover-class="none">

      </navigator>
    </view> -->
		<view class="panel-hot" v-else>
			<view class="item" @click="navigateToAIPage(record.recordOriginalId)">
				<view class="record-item">
					<view class="item-item"> {{record.createTime}}</view>
					<view class="info-card">
						<view class="title-text">
							<view class="title">微循环</view>
							<view class="number"> {{ record.recordDetails.微循环 }}</view>
						</view>
						<view class="title-text">
							<view class="title">收缩压</view>
							<view class="number"> {{ record.recordDetails.收缩压 }}</view>
						</view>
						<view class="title-text">
							<view class="title">血氧</view>
							<view class="number"> {{ record.recordDetails.血氧 }}</view>
						</view>
						<view class="title-text">
							<view class="title">心率</view>
							<view class="number"> {{ record.recordDetails.心率 }}</view>
						</view>
						<view class="title-text">
							<view class="title">舒张压</view>
							<view class="number"> {{ record.recordDetails.舒张压 }}</view>
						</view>
					</view>
				</view>
			</view>
      <view class="item">
      	<view class="record-item">
      		<view class="item-item"> 医生建议</view>
      		<view class="info-card">
      			<view class="title-text">
      				<view class="number1">  {{ doctorAdvice }} </view>
      			</view>
      		</view>
      	</view>
      </view>
		</view>
	</view>
   </scroll-view>
	<!-- 设备列表下拉框 -->
	<up-picker :show="deviceShow" :columns="deviceData" :closeOnClickOverlay="true" @close="selectClose"
		@confirm="deviceBtn" keyName="deviceName" @cancel="selectClose"></up-picker>
	<!-- 更改设备使用者下拉框 -->
	<up-picker :show="userDeviceShow" :columns="userColumns" :closeOnClickOverlay="true" keyName="userName"
		@confirm="userSelctBtn" @close="userSelectClose" @cancel="userSelectClose"></up-picker>
	<!-- timeColumns -->
	<up-picker :show="userTimeShow" :columns="timeColumns" :closeOnClickOverlay="true" keyName="createTime"
		@confirm="timeSelctBtn" @close="timeSelectClose" @cancel="timeSelectClose">
    </up-picker>
</template>
<style lang="scss" scoped>
	.card {
		background-color: #A5DD9B;
		border-radius: 20px;
		padding: 10px;
		width: 140px;
		height: 50px;

		text {
			font-size: 20px;
      text-align: center;
      color: white;
      font-size: 26rpx;
		}
	}
	.item-container {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		align-items: flex-start;
		/* 垂直居中 */
	}
	page {
		background-color: #f7f7f7;
		height: 100%;
		display: flex;
		flex-direction: column;
	}
	// 头部样式
	.navbar {
		// background-image: url(@/static/images/navigator_bg.png);
		background-color: #e9e7ef;
		background-size: cover;
		position: relative;
		display: flex;
		flex-direction: column;
		padding-top: 20px;

		.logo {
			display: flex;
			align-items: center;
			height: 64rpx;
			padding-left: 30rpx;
			padding-top: 20rpx;

			.logo-image {
				width: 166rpx;
				height: 39rpx;
			}

			.logo-text {
				flex: 1;
				line-height: 28rpx;
				color: #fff;
				margin: 2rpx 0 0 20rpx;
				padding-left: 20rpx;
				border-left: 1rpx solid #fff;
				font-size: 26rpx;
			}
		}

		.search {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 10rpx 0 26rpx;
			height: 64rpx;
			margin: 16rpx 20rpx;
			color: #fff;
			font-size: 28rpx;
			border-radius: 32rpx;
      background-color: #CCCCCC;
			// background-color: rgba(255, 255, 255, 0.5);
		}

		.icon-search {
			&::before {
				margin-right: 10rpx;
			}
		}

		.icon-scan {
			font-size: 30rpx;
			padding: 15rpx;
		}
	}


	// 选择列表区域
	.select-list {
		padding: 40rpx 25rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;


		.select-item {
      font-size: 28rpx;
	    background-color: #FFFFFF;
	    padding: 25rpx 25rpx;
	    display: flex;
	    border-radius: 30rpx;

		}
	}
	.scroll-view {
		flex: 1;
		padding: 40rpx 30rpx;
		height: 100%;



		// 设备信息
		.device-info {
			height: 200rpx;
			margin: 0 auto;
			margin-top: 60rpx;

			.form-row {
				text-align: center;
			}

			.form-buttons {
				margin-top: 30rpx;
				width: 260rpx;
			}
		}




		.login-blank {
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			height: 60vh;
      button{
         display: flex;
            justify-content: center;
              align-items: center;
              width: 100px;
              padding: 6px;
              line-height: 1.5;
              color: white;
              font-size: 28rpx;
              border-radius: 20rpx;
              background-color: #A5DD9B;
      }
		}

		//列表
		.panel-hot {

			// bottom: -20px;
			.item {
				width: 100%;
				height: 240rpx;
				margin-bottom: 25px;
				background-color: #FFFFFF;
				/* 卡片背景色 */
				border-radius: 20rpx;

				.record-item {
					padding: 10px;

					.item-item {
						text-align: center;
					}

					.info-card {
						display: flex;
						justify-content: space-between;
						align-items: center;
						// height: 220rpx;
						margin-top: 10rpx;
						.title-text {
							font-size: 35rpx;
							text-align: center;
              .number1{
                  font-size: 35rpx;
              }
							.title {
								margin-bottom: 20rpx;
							}
						}
					}
				}

			}

		}
	}
  .scroll-view.data-v-83a5a03c{
    background-color: #f0f0f4;
  }
</style>
